/**
 *    Copyright 2009-2016 the original author or authors.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package org.apache.ibatis.logging;

import java.lang.reflect.Constructor;

/**
 * 日志工厂类（工具类），供其他模块快速获取日志类实例对象，
 * 	比如：private static final Log log = LogFactory.getLog(JdbcTransaction.class);
 * @author Clinton Begin
 * @author Eduardo Macarron
 */
public final class LogFactory {

  /**
   * Marker to be used by logging implementations that support markers
   */
  public static final String MARKER = "MYBATIS";
  /**
   * 记录当前使用的第三方日志组件所对应的适配器的构造方法
   */
  private static Constructor<? extends Log> logConstructor;
  /**
   * 尝试获取日志实现，
   * 	依次尝试获取SLF4J、Apache Commons Logging、Log4j2、Log4j、JDK logging类型的日志实现，
   * 	当已经获取到日志实现后，后续的实现就会被忽略。
   */
  static {
    tryImplementation(new Runnable() {
      @Override
      public void run() {
        useSlf4jLogging();
      }
    });
    tryImplementation(new Runnable() {
      @Override
      public void run() {
        useCommonsLogging();
      }
    });
    tryImplementation(new Runnable() {
      @Override
      public void run() {
        useLog4J2Logging();
      }
    });
    tryImplementation(new Runnable() {
      @Override
      public void run() {
        useLog4JLogging();
      }
    });
    tryImplementation(new Runnable() {
      @Override
      public void run() {
        useJdkLogging();
      }
    });
    tryImplementation(new Runnable() {
      @Override
      public void run() {
        useNoLogging();
      }
    });
  }
  /**
   * 私有构造器，禁止new实例对象
   */
  private LogFactory() {
    // disable construction
  }
  /**
   * 创建Log对象，底层通过{@link #getLog(String)}实现
   * @param aClass 需要启用日志实例的类
   * @return
   */
  public static Log getLog(Class<?> aClass) {
    return getLog(aClass.getName());
  }
  /**
   * 创建Log对象
   * @param logger  array of objects to be passed as arguments to
   * the constructor call; values of primitive types are wrapped in
   * a wrapper object of the appropriate type (e.g. a {@code float}
   * in a {@link java.lang.Float Float})
   * @return
   */
  public static Log getLog(String logger) {
    try {
      return logConstructor.newInstance(logger);
    } catch (Throwable t) {
      throw new LogException("Error creating logger for logger " + logger + ".  Cause: " + t, t);
    }
  }
  /**
   * 自定义日志实现，初始化日志构造器
   * synchronized 保证logConstructor是单例对象
   * @param clazz
   */
  public static synchronized void useCustomLogging(Class<? extends Log> clazz) {
    setImplementation(clazz);
  }
  /**
   * 启用slf4j日志实现
   */
  public static synchronized void useSlf4jLogging() {
    setImplementation(org.apache.ibatis.logging.slf4j.Slf4jImpl.class);
  }
  /**
   * 启用org.apache.commons.logging.Log日志实现
   */
  public static synchronized void useCommonsLogging() {
    setImplementation(org.apache.ibatis.logging.commons.JakartaCommonsLoggingImpl.class);
  }
  /**
   * 启用org.apache.log4j.Logger日志实现
   */
  public static synchronized void useLog4JLogging() {
    setImplementation(org.apache.ibatis.logging.log4j.Log4jImpl.class);
  }
  /**
   * 启用org.apache.logging.log4j.Logger日志实现
   */
  public static synchronized void useLog4J2Logging() {
    setImplementation(org.apache.ibatis.logging.log4j2.Log4j2Impl.class);
  }
  /**
   * 启用java.util.logging.Logger日志实现，即JDK自带的日志实现
   */
  public static synchronized void useJdkLogging() {
    setImplementation(org.apache.ibatis.logging.jdk14.Jdk14LoggingImpl.class);
  }
  /**
   * 启用日志实现，该实现方法只是在控制台打印了日志信息
   */
  public static synchronized void useStdOutLogging() {
    setImplementation(org.apache.ibatis.logging.stdout.StdOutImpl.class);
  }
  /**
   * 启用NoLoggingImpl日志实现，即不启用日志功能
   */
  public static synchronized void useNoLogging() {
    setImplementation(org.apache.ibatis.logging.nologging.NoLoggingImpl.class);
  }
  /**
   * 尝试获取日志实现，在静态代码块中，
   * 	依次尝试获取SLF4J、Apache Commons Logging、Log4j2、Log4j、JDK logging类型的日志实现，
   * 	当已经获取到日志实现后，后续的实现就会被忽略。
   * @param runnable
   */
  private static void tryImplementation(Runnable runnable) {
    if (logConstructor == null) {
      try {
        runnable.run();
      } catch (Throwable t) {
        // ignore
      }
    }
  }
  /**
   * 设置日志的实现类
   * @param implClass
   */
  private static void setImplementation(Class<? extends Log> implClass) {
    try {
      Constructor<? extends Log> candidate = implClass.getConstructor(String.class);
      Log log = candidate.newInstance(LogFactory.class.getName());
      if (log.isDebugEnabled()) {
        log.debug("Logging initialized using '" + implClass + "' adapter.");
      }
      logConstructor = candidate;
    } catch (Throwable t) {
      throw new LogException("Error setting Log implementation.  Cause: " + t, t);
    }
  }

}
